import { GetMoreImg, GetOrderDetail, UpdateMoreImg } from "../../../utils/data/apis";
import { event } from "../../../utils/interface";
import msg from "../../../utils/model/msg";

interface _OrderDetail {
  id: string, userid: string, courseid: string, coursename: string, endtime: string, isshow: string, order_num: string, payState: string, payendTime: string, registrationtime: string, sex: string, starttime: string, status: string, username: string,
  [key: string]: string,
}
interface _MoreImg {
  name: string, path: string,
  [key: string]: string
}
// pages/detail/apply/index.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderDetail: {},
    moreImg: [],
    orderStatus: '未知', // 订单状态
    id_flag: 'student', // 订单身份
    id: '', // 订单id
    showMore: false,
    TeaForStu: '',
  },
  /**
   * @function 展示材料
   */
  showMore: function() {
    this.setData({
      showMore: !this.data.showMore,
    })
  },

  /**
   * @function 拉取数据
   */
  getData: function (id: string, id_flag: string, TeaForStu: string | undefined) {
    this.setData({ id_flag, id, TeaForStu});
    msg.Loading();
    const order = getOrderDetail({ id, id_flag, TeaForStu })
      .then((res: _OrderDetail) => {
        const state = ['', '已取消', '待付款', '交易成功', '正在退款', '已退款', '已退款'];
        const TeaState = ['', '报名失败', '审核中', '报名成功', '', '', ''];
        this.setData({
          orderDetail: res,
          orderStatus: this.data.id_flag === 'teacher'? TeaState[parseInt(res.status)] :state[parseInt(res.status)],
        })
      })
    const img = getMoreImg({ id, id_flag, TeaForStu })
      .then((res: Array<_MoreImg>) => {
        const tmp: any = res;
        this.setData({
          moreImg: tmp,
        })
      })
    Promise.all([order, img])
      .then(() => { msg.HideLoading(); })
      .catch(async () => {
        msg.HideLoading();
        await msg.Modal('拉取数据失败');
        wx.navigateBack();
      })
  },

  /**
   * @function 修改补充图片资料
   */
  changeMoreImg: function () {
    if(!this.data.showMore) { 
      return;
    }
    changeMoreImg({ moreImg: this.data.moreImg }, (moreImg: any) => {
      this.updateMoreImg(moreImg, (moreImg: any) => {
        this.setData({
          moreImg: moreImg,
        })
      });
    })
  },
  /**
   * @function 删除补充图片资料
   */
  removeImg: function (e: event) {
    if(!this.data.showMore) { 
      return;
    }
    const id: any = e.currentTarget.dataset.id;
    const moreImg: Array<_MoreImg> = this.data.moreImg;
    moreImg.splice(id, 1);
    this.updateMoreImg(moreImg, (moreImg: any) => {
      this.setData({
        moreImg: moreImg,
      })
    });
  },
  /**
  * @function 上传更新
  */
  updateMoreImg: function (moreImg: _MoreImg[], callback?: (moreImg: _MoreImg[]) => void) {
    const { id, id_flag } = this.data;
    UpdateMoreImg({
      id: id,
      modelName: id_flag === 'teacher' ? 'TeaSignList' : 'SignList',
      more_file: JSON.stringify(moreImg),
    })
      .then(() => {
        msg.Success('更新成功');
        if(callback) callback(moreImg);
      })
      .catch(() => msg.Modal('更新出错'))
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { id, id_flag, TeaForStu } = options;
    if (!id || !id_flag) {
      msg.Fail('Err404');
      wx.navigateBack();
      return;
    }
    // if(undefined){
    //   console.log("underfined");
    // }
    // else if('')
    // {
    //   console.log("''");
    // }
    // else if('true'){
    //   console.log('true');
    // }
    this.getData(id, id_flag, TeaForStu);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})

/**
 * @function 获取图片补充材料
 */
const getMoreImg = (data: { id: string, id_flag: string, TeaForStu: string | undefined }): Promise<Array<_MoreImg>> => {
  return new Promise((resolve, reject) => {
    const modelName = data.id_flag == 'teacher' && data.TeaForStu != 'true' ? 'TeaSignList' : 'SignList';
    const id = data.id;
    GetMoreImg({
      id: id,
      modelName: modelName
    })
      .then((res: any) => {
        const moreImg: Array<_MoreImg> = res.data === "" ? [] : res.data;
        resolve(moreImg);
      })
      .catch(() => { reject(); })
  })
}

/**
 * @function 获取订单详情
 */
const getOrderDetail = (data: { id: string, id_flag: string, TeaForStu: string | undefined }): Promise<_OrderDetail> => {
  return new Promise((resolve, reject) => {
    GetOrderDetail({
      id: data.id,
      modelName: data.id_flag === 'teacher' ? (data.TeaForStu === 'true' ? 'SignList' :'TeaSignList') :'SignList',
    })
      .then((res: any) => {
        const orderDetail: _OrderDetail = res.data.data[0];
        resolve(orderDetail);
      })
      .catch(() => { reject(); })
  })
}
/**
 * @function 修改补充图片
 */
const changeMoreImg = (data: { moreImg: Array<_MoreImg> }, callback: (moreImg: Array<_MoreImg>) => void) => {
  const { moreImg } = data;
  wx.navigateTo({
    url: '../../order/material/index',
    events: {
      submit: (data: { img: string }) => {
        const img = JSON.parse(data.img);
        moreImg.push(...img); // 入栈
        callback(moreImg);
      }
    }
  })
}
